$(function () {
    //layui初始化，加载弹出层，表单等
    layui.use(['form', 'element', 'laydate', 'upload'], function () {
        layer = layui.layer;
        laydate = layui.laydate;
        element = layui.element;
        form = layui.form;
        upload = layui.upload;

        form.verify();

        $('.datetime').each(function () {
            laydate.render({elem: this, type: 'datetime', trigger: 'click'})
        });
        $('.date').each(function () {
            laydate.render({elem: this, type: 'date', trigger: 'click'})
        });
        $('.date_range').each(function () {
            laydate.render({elem: this, type: 'date',range: true, trigger: 'click'})
        });


        $('.config_laydate').each(function () {
            var format_1 = $(this).attr('data-format-1');
            var format_2 = $(this).attr('data-format-2');
			var range = format_2 == 1 ? false : true;
            laydate.render({elem: this, type: format_1,range: range, trigger: 'click'})
        });

        form.on('switch(switch)', function (obj) {
            var val = $(this).prop('checked');
            var url = $(this).attr('url');
            $.get(url, {val: val})
        })

        //修改单个字段
        $('.tableInput').change(function () {
            tableInput($(this));
        })

        form.on('select(tableInput)', function (obj) {
            tableInput($(obj.elem));
        });

        //添加配置页面，监听日期配置
        form.on('select(call_type)', function (obj) {
            switch (obj.value) {
                case '7':
                    $("#time_format").css('display', 'block');
                    $("#suffix").css('display', 'none');
                    break;
                case '8':
                case '1':
                    $("#suffix").css('display', 'block');
                    $("#time_format").css('display', 'none');
                    break;
                default:
                    $("#time_format").css('display', 'none');
                    $("#suffix").css('display', 'none');
                    break;
            }
        });

        function tableInput(obj) {
            var id = obj.attr('data-id');
            var title = obj.attr('data-title');
            var val = obj.val();
            var url = obj.attr('data-url');
            $.get(
                url,
                {id: id, val: val},
                function (data) {
                    // layer.msg('ID为'+id+'的'+title+'修改为'+val);
                    layer.msg('修改成功');
                }
            );
        }

        $('td').on('click', '.state', function () {
            var id = $(this).attr('data-id');
            var url = $(this).attr('url');
            var val = $(this).attr('data-value');
            layer.confirm($(this).attr('data-confirm'), function (index) {
                $.get(url, {id: id, val: val}, function (data) {
                    if (data.status == '0') {
                        layer.alert(data.message, function () {
                            window.location.reload();
                        })
                    } else {
                        window.location.reload();
                    }
                }, 'json')
            });
        })

        $('.stateAll').click(function () {
            var ids = tableCheck.getData();
            var val = $(this).attr('data-value');
            var url = $(this).attr('url');
            layer.confirm($(this).attr('data-confirm'), function (index) {
                $.get(url, {id: ids, val: val}, function (data) {
                    if (data.status == '0') {
                        layer.alert(data.message, function () {
                            window.location.reload();
                        })
                    } else {
                        window.location.reload();
                    }
                }, 'json')
            })
        })

        form.on('submit(save)', function (data) {
            // layer.load();
            var btn = $(this);
            btn.attr('disabled', true);
            formObj = $($(this).attr('formObj'));
            url = formObj.attr('action');
            $.ajax({
                type: 'POST',
                url: url,
                data: formObj.serialize(),
                dataType: "json",
                success: function (data) {
                    // layer.closeAll();
                    if (data.status == 1) {
                        layer.alert(data.message, function () {
                            
                            if (window.name != '') {
                                var index = parent.layer.getFrameIndex(window.name);
                                // console.log(index);return;
                                parent.layer.close(index);
                                location.reload();
                            } else {
                                location.reload();
                            }
                        });
                    } else {
                        layer.alert(data.message, function (index) {
                            layer.close(index);
                        });
                        btn.removeAttr('disabled');
                    }
                },
                error(e) {
                    btn.removeAttr('disabled');
                }
            });
            return false;
        })

        //单张图片上传
        upload.render({
            elem: '.uploadImage',
            url: '/ajax/Upload/upload_images',
            before: function (obj) {
                layer.load();
                var i = this.item.index('.uploadImage');
                obj.preview(function (index, file, result) {
                    $('.showImage:eq(' + i + ')').attr('src', result); //图片链接,上传后显示图片
                });
            },
            done: function (data) {
                layer.closeAll();
                if (data.code == 0) {
                    var i = this.item.index('.uploadImage');
                    $('.inpImage:eq(' + i + ')').val(data.data.src);
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            }
        });

        //多张上传
        upload.render({
            elem: '.uploadImages',
            url: '/ajax/Upload/upload_images',
            multiple: true,
            before: function (obj) {
                layer.load();
                var i = this.item.index('.uploadImages');
                obj.preview(function (index, file, result) {
                    $('.showImages:eq(' + i + ')').append('<div class="imgContainer uploadImageBoxes"><img src="' + result + '"><a href="javascript:;" class="uploadDels">删除</a></div>')
                });
            },
            done: function (data) {
                layer.closeAll();
                if (data.code == 0) {
                    var i = this.item.index('.uploadImages');
                    var inpName = this.item.attr('inpName');
                    $('.showImages:eq(' + i + ')').append('<input type="hidden" name="' + inpName + '[]" value="' + data.data.src + '" class="uploadInps"/>');
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            }
        });

        //单文件上传
        upload.render({
            elem: '.uploadFile',
            url: '/ajax/Upload/upload_file',
            accept: 'file',
            done: function (data) {
                if (data.code == 0) {
                    var i = this.item.index('.uploadFile');
                    $('.showFile:eq(' + i + ')').attr('href', data.data.src); //图片链接,上传后显示图片
                    $('.showFile:eq(' + i + ')').text(data.data.file_name);

                    $('.inpFile:eq(' + i + ')').val(data.data.src);
                    $('.inpFileName:eq(' + i + ')').val(data.data.file_name);
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            }
        });

        $('body').on('click', '.uploadDels', function () {
            var i = $(this).index('.uploadDels');
            $('.uploadImageBoxes:eq(' + i + ')').remove();
            $('.uploadInps:eq(' + i + ')').remove();
        })

        //上传视频
        $(".videoUploadBtn").click(function () {
            var obj = $(this);
            var i = $(this).index('.videoUploadBtn');
            var files = $('.videoFile:eq(' + i + ')').prop('files');
            $.get("/ajax/Qiniu/gettoken.html", function (data) {
                var domain = data.domain;
                var time = new Date().getTime();
                var filename = $('.videoFile:eq(' + i + ')').val();
                var index = filename.lastIndexOf('.');
                var File = new FormData();
                File.append('file', files[0]);
                File.append('token', data.token);
                File.append('key', time + filename.substring(index));

                // AJAX提交数据
                $.ajax({
                    url: 'http://up.qiniup.com',
                    type: 'POST',
                    data: File,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        $('.videoInp:eq(' + i + ')').val('http://' + domain + '/' + data.key);
                        $('.videoNameInp:eq(' + i + ')').val(files['0']['name'])
                        $('.videoLink:eq(' + i + ')').text(data.key);
                        $('.videoLink:eq(' + i + ')').attr('href', 'http://' + domain + '/' + data.key);
                        // 判断是否上传成功并设置相关表单
                        if (data.key) {
                            $('.videoInp:eq(' + i + ')').html(files['0']['name']);
                            layer.msg('上传成功');
                        } else {
                            layer.msg('上传失败');
                        }
                    }
                });
            });
        });
    });

    /*富文本编辑器*/
    $('.editor').each(function () {
        UE.getEditor($(this).attr('id'), {scaleEnabled: true});
    })

    /*列表页checkbox开始*/
    tableCheck = {
        init: function () {
            layui.use('form', function () {
                layui.form.on('checkbox(list_all)', function (obj) {
                    var checked = obj.elem.checked;
                    $("[lay-filter=list_checkbox]").prop("checked", checked);
                    layui.form.render('checkbox');
                })
            })
        },
        getData: function () {
            var arr = [];
            $("[lay-filter=list_checkbox]:checked").each(function (i, e) {
                arr.push($(this).val());
            });
            return arr;
        }
    }

    //开启表格多选
    tableCheck.init();
    /*列表页checkbox结束*/

    //触发事件
    var tab = {
        tabAdd: function (title, url, id) {
            //新增一个Tab项
            element.tabAdd('xbs_tab', {
                title: title
                ,
                content: '<iframe tab-id="' + id + '" frameborder="0" src="' + url + '" scrolling="yes" class="x-iframe"></iframe>'
                ,
                id: id
            })
        }
        , tabDelete: function (othis) {
            //删除指定Tab项
            element.tabDelete('xbs_tab', '44'); //删除：“商品管理”
            othis.addClass('layui-btn-disabled');
        }
        , tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange('xbs_tab', id); //切换到：用户管理
        }
    };

    $('.container .left_open i').click(function (event) {
        if ($('.left-nav').css('left') == '0px') {
            $('.left-nav').animate({left: '-221px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        } else {
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '221px'}, 100);
            if ($(window).width() < 768) {
                $('.page-content-bg').show();
            }
        }
    });

    $('.page-content-bg').click(function (event) {
        $('.left-nav').animate({left: '-221px'}, 100);
        $('.page-content').animate({left: '0px'}, 100);
        $(this).hide();
    });

    $('.layui-tab-close').click(function (event) {
        $('.layui-tab-title li').eq(0).find('i').remove();
    });

    // 栏目多级显示效果
    var cateIds = [];

    function getCateId(cateId) {
        $("tbody tr[fid=" + cateId + "]").each(function (index, el) {
            id = $(el).attr('cate-id');
            cateIds.push(id);
            getCateId(id);
        });
    }

    $("tbody.x-cate tr[level!='0']").hide();

    //修改字段状态
    $('.x-show').click(function () {
        if ($(this).attr('status') == 'true') {
            $(this).html('&#xe625;');
            $(this).attr('status', 'false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid=" + cateId + "]").show();
        } else {
            cateIds = [];
            $(this).html('&#xe623;');
            $(this).attr('status', 'true');
            cateId = $(this).parents('tr').attr('cate-id');
            getCateId(cateId);
            for (var i in cateIds) {
                $("tbody tr[cate-id=" + cateIds[i] + "]").hide().find('.x-show').html('&#xe623;').attr('status', 'true');
            }
        }
    })

    //左侧菜单效果
    // $('#content').bind("click",function(event){
    $('.left-nav #nav li').click(function (event) {
        if ($(this).children('.sub-menu').length) {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
                $(this).find('.nav_right').html('&#xe697;');
                $(this).children('.sub-menu').stop().slideUp();
                $(this).siblings().children('.sub-menu').slideUp();
            } else {
                $(this).addClass('open');
                $(this).children('a').find('.nav_right').html('&#xe6a6;');
                $(this).children('.sub-menu').stop().slideDown();
                $(this).siblings().children('.sub-menu').stop().slideUp();
                $(this).siblings().find('.nav_right').html('&#xe697;');
                $(this).siblings().removeClass('open');
            }
        } else {
            var url = $(this).children('a').attr('_href');
            var title = $(this).find('cite').html();
            var index = $('.left-nav #nav li').index($(this));

            for (var i = 0; i < $('.x-iframe').length; i++) {
                if ($('.x-iframe').eq(i).attr('tab-id') == index + 1) {
                    $('.x-iframe').eq(i).attr('src', url);
                    tab.tabChange(index + 1);
                    event.stopPropagation();
                    return;
                }
            }
            ;
            tab.tabAdd(title, url, index + 1);
            tab.tabChange(index + 1);
        }
        event.stopPropagation();
    })
})

/*弹出层*/
function show(title, url, w, h) {
    if (title == null || title == '') title = false;
    if (url == null || url == '') url = "404.html";
    if (w == null || w == '' || $(window).width() < w) w = ($(window).width() * 0.9);
    if (h == null || h == '' || $(window).height() < h) h = ($(window).height() - 50);
    var index = layer.open({
        type: 2,
        area: [w + 'px', h + 'px'],
        fix: false, //不固定
        maxmin: false,
        shadeClose: true,
        shade: 0.4,
        title: title,
        content: url
    });
}
